package com.ms.infrastructure.spring;

import com.ms.domain.validator.ValidationService;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.beans.factory.support.BeanDefinitionBuilder;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.beans.factory.support.BeanDefinitionRegistryPostProcessor;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;
import org.springframework.validation.beanvalidation.LocalValidatorFactoryBean;

/**
 * User: gmc
 * Date: 14/03/13
 */
@Component
public class ValidatorRegistryPostProcessor implements BeanDefinitionRegistryPostProcessor, BeanPostProcessor, ApplicationContextAware {

    private final String VALIDATION_SERVICE_NAME = "validationService";
    private final String VALIDATOR_NAME = "validator";
//    private final String VALIDATOR_ERROR_MSG_SOURCE = "validatorErrorMsgSource";

    public void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry registry) throws BeansException {
        registry.registerBeanDefinition(VALIDATOR_NAME, BeanDefinitionBuilder.rootBeanDefinition(LocalValidatorFactoryBean.class).getBeanDefinition());
        registry.registerBeanDefinition(VALIDATION_SERVICE_NAME, BeanDefinitionBuilder.rootBeanDefinition(ValidationService.class).getBeanDefinition());
//        registry.registerBeanDefinition(VALIDATOR_ERROR_MSG_SOURCE, BeanDefinitionBuilder.rootBeanDefinition(ResourceBundleMessageSource.class).getBeanDefinition());
    }

    public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {
    }

    public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
//        if (VALIDATOR_ERROR_MSG_SOURCE.equals(beanName)) {
//            ResourceBundleMessageSource messageSource = (ResourceBundleMessageSource) bean;
//            messageSource.setBasename("com.dpwc.i18n.errorMessages");
//        }
//        if (VALIDATION_SERVICE_NAME.equals(beanName)) {
//            Map<String, Validator> beansOfType = appCtx.getBeansOfType(Validator.class);
//            ConversionServiceFactoryBean conversionfactoryBean = (ConversionServiceFactoryBean) bean;
//            Set converters = new HashSet(beansOfType.values());
//            conversionfactoryBean.setConverters(converters);
//        }
        return bean;
    }

    public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
        return bean;
    }

    ApplicationContext appCtx;

    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        appCtx = applicationContext;
    }

}
